<template>
	<div id="container">
		<el-dropdown
			class="dropdown-note"
			:class="isChosen == true ? 'chosen' : ''"
			trigger="click"
			@command="handleCommand"
		>
			<span class="el-dropdown-link title">
				发布公告
				<i class="el-icon-arrow-down el-icon--right"></i>
			</span>
			<el-dropdown-menu slot="dropdown">
				<el-dropdown-item command="on">
					<img src="img/信息公告.png" alt="" />
					激活发布
				</el-dropdown-item>
				<el-dropdown-item command="off">
					<img src="img/关闭_操作_jurassic.png" alt="" />
					关闭发布
				</el-dropdown-item>
				<el-dropdown-item command="manage">
					<category-management theme="outline" size="16" fill="#333" />
					公告管理
				</el-dropdown-item>
			</el-dropdown-menu>
		</el-dropdown>
		<!-- <button id="btn" @click="dialogVisible = true">发布公告</button> -->
		<el-dialog
			class="dialog"
			title="发布公告"
			:visible.sync="dialogVisible"
			width="38%"
			append-to-body
			:modal="false"
			:close-on-click-modal="false"
			@close="cancelPost"
			v-dialogDrag
		>
			<div class="div-search">
				<input
					class="search-input"
					type="text"
					v-model="searchValue"
					@input="handleinput"
					placeholder="请输入关键字"
				/>
			</div>
			<div class="dia-content">
				<el-table :data="bufferInfo" stripe border highlight-current-row>
					<el-table-column
						property="index"
						label="序号"
						width="145"
						align="center"
					></el-table-column>
					<el-table-column
						property="name"
						label="受影响地区"
						width="260"
						align="center"
					></el-table-column>
					<el-table-column
						property="phonenumber"
						label="物业电话"
						width="260"
						align="center"
					></el-table-column>
				</el-table>
				<el-pagination
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="page"
					:page-sizes="[3, 5, 10]"
					:page-size="size"
					layout="total, sizes, prev, pager, next, jumper"
					:total="searchValue ? resutofsearch.length : infoAll.length"
				></el-pagination>
				<div class="div-input">
					<p>公告信息：</p>
					<el-input
						type="textarea"
						autosize
						v-model="note"
						placeholder="请输入公告"
					></el-input>
				</div>
			</div>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancelPost">取消发布</el-button>
				<el-button type="primary" @click="postNote">确定发布</el-button>
			</span>
		</el-dialog>
		<note-manage ref="child"></note-manage>
	</div>
</template>

<script>
import { CategoryManagement } from '@icon-park/vue';
import { mapState } from 'vuex';
import { Query } from '../../../utils/Query.js';
import NoteManage from './NoteManage.vue';
export default {
	name: 'PostNote',
	components: {
		NoteManage,
		CategoryManagement,
	},
	data() {
		return {
			isChosen: false, //激活菜单样式
			dialogVisible: false, //控制弹窗
			service: { docName: 'guanggu', layerId: 0 },
			isdrawRoadbuffer: false, //是否处于绘制缓冲线阶段  如果处于该阶段，不能再点击发布公告
			BaseUrl: 'gdbp://MapGisLocal/wuhan/sfcls/',
			bufferUrl: '',
			clipBufferUrl: '', // 最终裁剪后缓冲区的url
			bufferInfo: [], // 查询的缓冲区与居民区相交的要素信息,用于绑定table
			infoAll: [], //bufferInfo的全部数据，用于备份
			resutofsearch: [], //存储搜索结果
			source: null, //绘制画笔的数据源
			note: '', //交管用户输入的公告
			searchValue: '',
			page: 1,
			size: 3, // 每页显示数
		};
	},
	computed: mapState(['map', 'docLayer', 'userId']),

	methods: {
		handleCommand(command) {
			if (command == 'on') {
				this.isChosen = true;
				this.drawNoteRoads();
			} else if (command == 'off') {
				this.isChosen = false;
				this.dialogVisible = false;
				this.$router.go(0);
			} else if (command == 'manage') {
				console.log(123);
				this.nodtmangeshow();
			}
		},
		nodtmangeshow() {
			/* 调用子组件的方法 */
			this.$refs.child.openDialog();
		},
		drawNoteRoads() {
			// 点击发布公告按钮后
			/* 1 交通用户绘制发生情况的道路线要素 */
			// 弹窗确认
			if (!this.isdrawRoadbuffer) {
				this.$confirm('请在显示的居民区内添加状况道路', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						this.queryResident();
					})
					.catch(() => {
						this.$message({
							showClose: true,
							type: 'info',
							duration: 2000, //消失时间设置为2秒
							message: '已取消添加',
						});
					});
			} else {
				this.$message({
					showClose: true,
					type: 'warning',
					duration: 2000, //消失时间设置为2秒
					message: '当前在绘制缓冲区！请勿重复点击',
				});
			}
		},
		/* 查询居民区 */
		queryResident() {
			Query.queryAreas({
				service: this.service,
				callback: this.queryAreasSuccess,
			});
		},
		// 查询居民区后的回调
		queryAreasSuccess(result) {
			//初始化Zondy.Format.PolygonJSON类
			var format = new Zondy.Format.PolygonJSON();
			//将MapGIS要素JSON反序列化为ol.Feature类型数组
			var features = format.read(result);

			let drawLayers = [];
			for (let i = 0; i < features.length; i++) {
				// 定义居民区的随机颜色
				let R = parseInt(Math.random() * 256);
				let G = parseInt(Math.random() * 256);
				let B = parseInt(Math.random() * 256);
				let randcolor = `rgb(${R},${G},${B})`;
				let drawSource = new ol.source.Vector({
					wrapX: false,
				});
				drawSource.addFeatures([features[i]]);
				let drawLayer = new ol.layer.Vector({
					source: drawSource,
					title: '居民区高亮',
					style: new ol.style.Style({
						fill: new ol.style.Fill({
							color: randcolor,
						}),
						//边线样式
						stroke: new ol.style.Stroke({
							color: 'blue',
							width: 1,
						}),
					}),
				});
				drawLayers.push(drawLayer);
			}

			drawLayers.map((item) => {
				this.map.addLayer(item);
			});
			/* 渲染完成后切换中心点至居民区 */
			let view = this.map.getView();
			view.setZoom(16);
			view.setCenter([114.392, 30.492]);

			// // 绘制完毕后，添加交互式画笔，绘制道路缓冲区
			this.isdrawRoadbuffer = true;
			this.drawRoadlines();
		},
		/* 绘制道路线 */
		drawRoadlines() {
			this.source = new ol.source.Vector({
				wrapX: false, //false 让地图 x 不能无限拉长
			});
			const layer = new ol.layer.Vector({
				source: this.source,
			});
			this.map.addLayer(layer);
			//  添加画笔
			let draw = new ol.interaction.Draw({
				source: this.source,
				type: 'LineString', // 线类型
			});
			// 激活画笔
			this.map.addInteraction(draw);
			draw.on('drawend', (e) => {
				console.log(e.feature.getGeometry().getCoordinates());
				let pointarr = e.feature.getGeometry().getCoordinates();
				var pointObj = [];
				pointarr.map((item) =>
					pointObj.push(new Zondy.Object.Point2D(item[0], item[1]))
				);
				/* 绘制完成后根据绘制的线生成缓冲区 */
				this.map.removeInteraction(draw);
				this.get_buffer_byRoadlines(pointObj);
			});
		},
		/* 基于绘制的道路线生成缓冲区*/
		get_buffer_byRoadlines(pointObj) {
			//构成折线的弧段
			let gArc = new Zondy.Object.Arc(pointObj);
			//构成线的折线
			let gAnyLine = new Zondy.Object.AnyLine([gArc]);
			//设置线要素的几何信息
			let gline = new Zondy.Object.GLine(gAnyLine);
			//设置要素的几何信息
			let fGeom = new Zondy.Object.FeatureGeometry({ LinGeom: [gline] });
			//设置属性结构
			const regAttStr = new Zondy.Object.CAttStruct({
				FldName: ['ID', '周长', 'LayerID'],
				FldNumber: 3,
				FldType: ['FldLong', 'FldDouble', 'FldLong'],
			});
			const values = [1, 0.132101984752282, 8];
			//实例化CAttDataRow类
			const valuesRow = new Zondy.Object.CAttDataRow(values, 1);
			//实例化FeatureBuffBySingleRing类，设置要素缓冲分析必要参数，输出分析结果到缓冲分析结果图层
			const clsBufBySR = new Zondy.Service.FeatureBuffBySingleRing({
				ip: 'localhost',
				port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
				//设置要素缓冲分析左半径
				leftRad: 0.001,
				//设置要素缓冲分析右半径
				rightRad: 0.001,
			});
			let resultName = this.BaseUrl + 'buffer' + Date.now();
			this.bufferUrl = resultName;
			/*设置缓冲分析参数*/
			//设置几何信息
			clsBufBySR.sfGeometryXML = JSON.stringify([fGeom]);
			//设置属性结构
			clsBufBySR.attStrctXML = JSON.stringify(regAttStr);
			//设置属性值
			clsBufBySR.attRowsXML = JSON.stringify([valuesRow]);
			//设置追踪半径
			clsBufBySR.traceRadius = 0.0001;
			//设置缓冲结果的名称以及存放地址
			clsBufBySR.resultName = resultName;

			//调用Zondy.Service.AnalysisBase基类的execute方法执行要素缓冲分析
			clsBufBySR.execute(this.bufferSuccess, 'post', false, 'json');
		},
		// 将缓冲区添加到图层
		bufferSuccess(result) {
			console.log(result);
			console.log(this.bufferUrl);
			if (result.succeed) {
				const resultLayer = new Zondy.Map.GdbpLayer('', [this.bufferUrl], {
					ip: 'localhost',
					port: 6163,
					isBaseLayer: false,
				});
				// this.map.addLayer(resultLayer)
				this.clipBufferbyResident();
			}
		},
		// 对缓冲区进行裁剪，将缓冲区与居民区相交的部分保留下来
		clipBufferbyResident() {
			this.clipBufferUrl = this.BaseUrl + 'ClipBuffer' + Date.now();
			//实例化ClipByLayer类
			const clipParam = new Zondy.Service.ClipByLayer({
				ip: 'localhost',
				port: '6163',
				//源居民区的URL
				srcInfo1: this.BaseUrl + '居民区',
				//裁剪缓冲区的URL
				srcInfo2: this.bufferUrl,
				//设置结果URL
				desInfo: this.clipBufferUrl,
				infoOptType: 0,
			});
			//调用基类的execute方法，执行图层裁剪分析。Success为成功回调函数
			clipParam.execute(this.clipSuccess, 'post', false, 'json');
		},
		clipSuccess(result) {
			if (result.succeed) {
				//将结果图层添加到地图视图中显示
				const resultClipLayer = new Zondy.Map.GdbpLayer(
					'',
					[this.clipBufferUrl],
					{
						ip: 'localhost',
						port: '6163', //访问IGServer的端口号，.net版为6163，Java版为8089,
						crossOrigin: 'Anonymous',
					}
				);
				this.map.addLayer(resultClipLayer);
				this.queryBufferInfo();
			} else {
				alert('叠加分析失败，请检查参数！');
			}
		},
		/* 裁剪成功后，查询缓冲区图层的信息 */
		queryBufferInfo() {
			Query.querybygdbUrl(this.clipBufferUrl, this.queryBufferSuccess);
		},
		queryBufferSuccess(result) {
			// console.log(result.SFEleArray)
			if (result.SFEleArray.length != 0) {
				result.SFEleArray.map((i, index) => {
					const item = {};
					item.index = index + 1;
					item.name = i.AttValue[4];
					item.phonenumber = i.AttValue[5];
					this.bufferInfo.push(item);
				});
				this.infoAll = this.bufferInfo;
				this.getCategory();
				this.dialogVisible = true;
				// console.log(this.bufferInfo)
			} else {
				// console.log('空')
				this.$confirm('缓冲区里没有包含居民区,是否重新添加', '提示', {
					confirmButtonText: '重新添加',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						/* 重新添加则再次调用函数 */
						this.source.clear();
						this.drawRoadlines();
					})
					.catch(() => {
						/* 取消则刷新页面 */
						this.$router.go(0);
					});
			}
		},
		/* 确定发布公告 */
		postNote() {
			if (this.note) {
				const affected_area = this.bufferInfo
					.map((item) => {
						return item.name;
					})
					.join(',');
				this.$http
					.post('/notice', {
						user_id: this.userId,
						notice_content: this.note,
						affected_area: affected_area,
					})
					.then((res) => {
						const { code } = res;
						if (code == 0) {
							this.$message.success('发布公告成功');
						}
					});
				this.dialogVisible = false;
				/* 发布完成后刷新页面 */
				this.$router.go(0);
			} else {
				this.$confirm('您还没有添加公告信息，请确认输入', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				});
			}
		},
		/* 取消发布公告 */
		cancelPost() {
			this.dialogVisible = false;
			this.$router.go(0);
		},

		/* 搜索框变化时触发的事件 */
		handleinput() {
			this.bufferInfo = this.infoAll;

			let str = ['', ...this.searchValue, ''].join('.*');
			let reg = new RegExp(str);
			this.bufferInfo = this.bufferInfo.filter(
				(item) =>
					reg.test(item.name) ||
					reg.test(item.phonenumber) ||
					reg.test(item.name + item.phonenumber)
			);
			this.resutofsearch = this.bufferInfo;
			// this.handleCurrentChange(this.page)
			// this.handleSizeChange(this.size)
			this.getCategory();
		},
		/* 分页相关方法 */
		handleCurrentChange(p) {
			this.page = p;
			// 重新获取新的分页数据
			this.getCategory();
		},
		handleSizeChange(s) {
			this.size = s;
			this.getCategory();
		},
		getCategory() {
			const start = (this.page - 1) * this.size; //起始下标（包含）
			const end = (this.page - 1) * this.size + this.size; //结束下标（不包含）
			if (!this.searchValue) {
				this.bufferInfo = this.infoAll.slice(start, end);
			} else {
				this.bufferInfo = this.resutofsearch.slice(start, end);
			}
		},
	},
};
</script>

<style scoped>
.chosen {
	/* 激活菜单样式 */
	background-color: antiquewhite !important;
	color: darkcyan !important;
}
.dropdown-note {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 0 5px;
	z-index: 11;
	border-radius: 10px;
	border-bottom: 2px solid white;
	font-size: 16px;
	font-weight: 500;
	background-color: rgba(248, 248, 132, 0.7);
}
.title {
	font-size: 18px;
}
.dropdown-note:hover {
	cursor: pointer;
	font-weight: 900;
	background-color: antiquewhite;
	color: darkcyan;
	box-shadow: 1px 1px 0px 0px;
	transition: all 0.2s ease-in-out;
}

.dia-content {
	width: 680px;
	margin-top: 40px;
	margin-bottom: 20px;
}
.div-search {
	margin-bottom: 10px;
	width: 680px;
	display: flex;
	justify-content: right;
}
.div-search .search-input {
	width: 200px;
	height: 30px;
	border: 1px solid rgb(75, 79, 72);
	outline: none;
	border-radius: 7px;
	padding-left: 10px;
}
/* .el-table {
	width: 680px !important;
}
.div-input {
	width: 680px;
} */
/* 用来设置当前页面element全局table 选中某行时的背景色*/
.el-table__body tr.current-row > td {
	background-color: rgba(171, 198, 239, 0.5) !important;
	transition: all 0.3s ease;
	font-weight: 900;
	/* 设置文字颜色，可以选择不设置 */
}
.el-table__row:hover {
	cursor: pointer;
}
/* 鼠标悬浮某一行的颜色 */
.el-table__row:hover .el-table__cell {
	background-color: rgb(227, 245, 217) !important;
}
</style>
